<template>
  <view class="container">
    <view class="login-box">
      <view class="logo">
        <image src="/static/images/logo.png" mode="aspectFit"></image>
        <text class="app-name">水滴记</text>
      </view>
      
      <view class="form-box">
        <u-form :model="form" ref="uForm">
          <u-form-item>
            <u-input 
              v-model="form.username" 
              placeholder="请输入用户名/手机号" 
              prefixIcon="account" 
              maxlength="20"
            ></u-input>
          </u-form-item>
          
          <u-form-item>
            <u-input 
              v-model="form.password" 
              placeholder="请输入密码（不少于8位）" 
              prefixIcon="lock" 
              type="password"
            ></u-input>
          </u-form-item>
        </u-form>
        
        <view class="tips-box">
          <view class="forget-pwd" @click="goForgetPwd">忘记密码?</view>
        </view>
        
        <view class="btn-box">
          <u-button type="primary" text="登录" @click="handleLogin" :loading="loading"></u-button>
          <u-button type="info" text="注册" plain @click="goRegister"></u-button>
        </view>
        
        <view class="other-login">
          <view class="divider">
            <view class="line"></view>
            <text>其他登录方式</text>
            <view class="line"></view>
          </view>
          
          <view class="icon-box">
            <view class="icon-item" @click="handleWechatLogin">
              <u-icon name="weixin-fill" color="#07c160" size="40"></u-icon>
              <text>微信登录</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex'
import { login } from '@/api/user'

// 导入TOKEN_NAME常量，与request.js保持一致
const TOKEN_NAME = 'wn_satoken';

export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      loading: false
    }
  },
  methods: {
    ...mapActions('user', ['setLoginStatus', 'setUserInfo']),
    
    // 验证密码
    validatePassword(password) {
      // 验证密码长度
      if (password.length < 8) {
        return {
          valid: false,
          message: '密码长度不能少于8位'
        };
      }
      
      return {
        valid: true,
        message: ''
      };
    },
    
    // 处理登录
    handleLogin() {
      console.log('点击登录按钮');
      
      // 用户名验证
      if (!this.form.username) {
        uni.showToast({
          title: '请输入用户名或手机号',
          icon: 'none'
        });
        return;
      }
      
      // 密码验证
      if (!this.form.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        });
        return;
      }
      
      const passwordValidation = this.validatePassword(this.form.password);
      if (!passwordValidation.valid) {
        uni.showToast({
          title: passwordValidation.message,
          icon: 'none'
        });
        return;
      }
      
      this.loading = true;
      console.log('开始登录请求，参数:', this.form);
      
      // 使用API函数发送请求
      login(this.form)
        .then(res => {
          console.log('登录成功，响应:', res);
          
          // 确保res是对象
          const userData = typeof res === 'object' ? res : {};
          
          // 获取token (可能在不同位置)
          const token = userData.token || userData.tokenValue || (userData.tokenInfo && userData.tokenInfo.tokenValue);
          
          if (!token) {
            console.error('未找到有效的token');
            uni.showToast({
              title: '登录成功但未获取到有效凭证',
              icon: 'none'
            });
            return;
          }
          
          // 使用正确的TOKEN_NAME存储token
          uni.setStorageSync(TOKEN_NAME, token);
          console.log(`已存储token到${TOKEN_NAME}:`, token);
          
          // 更新Vuex状态
          this.setLoginStatus(true);
          this.setUserInfo(userData);
          
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          });
          
          // 返回上一页或首页
          setTimeout(() => {
            uni.navigateBack({
              fail: () => {
                uni.switchTab({
                  url: '/pages/index/index'
                });
              }
            });
          }, 1500);
        })
        .catch(err => {
          console.error('登录请求失败:', err);
          uni.showToast({
            title: err.message || '登录失败，请检查用户名和密码',
            icon: 'none'
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 处理微信登录
    handleWechatLogin() {
      uni.showToast({
        title: '微信登录功能开发中',
        icon: 'none'
      });
    },
    
    // 跳转到注册页面
    goRegister() {
      uni.navigateTo({
        url: '/pages/user/register'
      });
    },
    
    // 跳转到忘记密码页面
    goForgetPwd() {
      uni.showToast({
        title: '忘记密码功能开发中',
        icon: 'none'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 40rpx;
}

.login-box {
  padding-top: 80rpx;
}

.logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
  
  image {
    width: 160rpx;
    height: 160rpx;
  }
  
  .app-name {
    margin-top: 20rpx;
    font-size: 36rpx;
    font-weight: bold;
    color: #2979ff;
  }
}

.form-box {
  padding: 20rpx;
}

.tips-box {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 40rpx;
  margin-top: 20rpx;
  
  .forget-pwd {
    font-size: 24rpx;
    color: #2979ff;
  }
}

.btn-box {
  margin-bottom: 60rpx;
  
  .u-button {
    margin-bottom: 30rpx;
  }
}

.other-login {
  margin-top: 60rpx;
  
  .divider {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
    
    .line {
      flex: 1;
      height: 1rpx;
      background-color: #eee;
    }
    
    text {
      padding: 0 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .icon-box {
    display: flex;
    justify-content: center;
    
    .icon-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 0 40rpx;
      
      text {
        margin-top: 10rpx;
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}
</style> 